package com.bm;


import com.future.util.ListNode;

import java.util.LinkedList;

/**
 * Description:
 *
 * @Author: future
 * @Date:2022/3/11:0:27
 */
public class BM11 {

    public static void main(String[] args) {
        ListNode head1 = new ListNode(9);
        head1.next = new ListNode(3);
        head1.next.next = new ListNode(7);
        ListNode head2 = new ListNode(6);
        head2.next = new ListNode(3);
        addInList(head1, head2);
    }

    public static ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        LinkedList<ListNode> stack1 = new LinkedList<>();
        LinkedList<ListNode> stack2 = new LinkedList<>();
        while (head1 != null) {
            stack1.addLast(head1);
            head1 = head1.next;
        }
        while (head2 != null) {
            stack2.addLast(head2);
            head2 = head2.next;
        }
        int jinwei = 0;
        ListNode ans = null;
        ListNode next = null;
        while (!stack1.isEmpty() && !stack2.isEmpty()) {
            int sum = stack1.pollLast().val + stack2.pollLast().val + jinwei;
            if (sum > 9) {
                jinwei = 1;
                sum = sum - 10;
            } else {
                jinwei = 0;
            }
            ans = new ListNode(sum);
            ans.next = next;
            next = ans;
        }
        ListNode result = null;
        ListNode tmp = null;
        ListNode t = null;
        if (!stack1.isEmpty()) {
            result = stack1.pollFirst();
            tmp = result;
            while (stack1.isEmpty()) {
                t = stack1.pollLast();

            }

        } else if (!stack2.isEmpty()) {
            result = stack2.pollFirst();
            tmp = result;
            if (tmp.next != null) {
                int s1 = tmp.next.val+jinwei;
                if (s1>9){
                    jinwei = 1;
                    s1 = s1 -10;
                }else {
                    jinwei = 0;
                }

            }
        }
        tmp.next = ans;
        return result;
    }
}
